package qe.spider.grab;

import cn.hutool.core.text.UnicodeUtil;
import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import qe.spider.vo.Stock;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


//查股网-自选股涨跌停
@Slf4j
public class GrabGubit_ZhangDieTing extends GrabGubit {

    private List<String> stockCodes;
    private String result;

    public GrabGubit_ZhangDieTing(List<String> stockCodes) {
        this.stockCodes = stockCodes;
    }

    public GrabGubit_ZhangDieTing() {
        stockCodes = new ArrayList<>();
    }

    //无用
    private FormBody formBody() {
        FormBody formBody = new FormBody.Builder()
                .add("zxtype", "1")
                .add("t", String.valueOf(Math.random()))
                .add("getfangan", "1")
                .build();
        return formBody;
    }


    public List<Stock> grab() {
        List<Stock> stocks = new ArrayList<>();
        for (int i = 0; i < stockCodes.size(); i++) {
            try {
                String code = stockCodes.get(i);
                List<Stock> ss = parseIsZhangDieTing(code, grab_Stock(code));
                stocks.addAll(ss);
            } catch (IOException e) {
                log.error("查询个股涨跌停时错误：{}", e.getMessage());
            }
        }
        return stocks;
    }

    public String grab_Stock(String code) throws IOException {
        String cookie = "gpai_auth=" + GrabGubit.cookies.get("gpai_auth") + "; PHPSESSID=" + GrabGubit.cookies.get("PHPSESSID") + "; user=" + GrabGubit.cookies.get("user") + "; zhuser=" + GrabGubit.cookies.get("zhuser");

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url("http://ddx.gubit.cn/xg/zhangting2021.php?stockid=" + code + "&t=0.31111086288082324&getfangan=1").get().header("Accept", " */*").header("Accept-Language", " zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6").header("Cache-Control", " no-cache").header("Connection", " keep-alive").header("Cookie", cookie).header("Host", " ddx.gubit.cn").header("Pragma", " no-cache").header("Referer", "http://ddx.gubit.cn/xg/zhangting.html").header("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0").header("X-Requested-With", " XMLHttpRequest")

                .build();
        Gson gson = new Gson();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);


            String result = UnicodeUtil.toString(response.body().string());
            this.result = result;
            log.info("涨停接口返回：{}", result);
            return result;
        }
    }


    public List<Stock> grab_ZiXuan() throws IOException {
        String cookie = "gpai_auth=" + GrabGubit.cookies.get("gpai_auth") + "; PHPSESSID=" + GrabGubit.cookies.get("PHPSESSID") + "; user=" + GrabGubit.cookies.get("user") + "; zhuser=" + GrabGubit.cookies.get("zhuser");

        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url("http://ddx.gubit.cn/xg/zhangting2021.php?zxtype=1&t=0.31111086288082324&getfangan=1&getzixuan=1")
                .get()
                .header("Accept", " */*")
                .header("Accept-Language", " zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .header("Cache-Control", " no-cache")
                .header("Connection", " keep-alive")
                .header("Cookie", getDefaultCookie())
                .header("Host", " ddx.gubit.cn")
                .header("Pragma", " no-cache")
                .header("Referer", "http://ddx.gubit.cn/xg/zhangting.html")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
                .header("X-Requested-With", " XMLHttpRequest")
                .build();
        Gson gson = new Gson();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);


            String result = UnicodeUtil.toString(response.body().string());
            this.result = result;
            log.info("涨停接口返回：{}", result);
            return parseIsZhangDieTing("", result);
        }
    }

    public List<Stock> parseIsZhangDieTing(String stockCode, String result) {
        try {
            List<Stock> stockList = new ArrayList<>();
            JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();

            JsonArray res = jsonObject.getAsJsonArray("data");
            if (null == res && !stockCode.isEmpty()) {
                stockList.add(new Stock().code(stockCode));
                return stockList;
            }
            Iterator<JsonElement> it = res.iterator();
            while (it.hasNext()) {
                JsonArray stocks = it.next().getAsJsonArray();
                String code = String.format("%06d", stocks.get(0).getAsInt());
                Integer zhangTingCnt5Day = stocks.get(2).getAsInt();
                Integer dieTingCnt5Day = stocks.get(10).getAsInt();
//                if (zhangTingCnt5Day > 0 || dieTingCnt5Day > 0) {
                stockList.add(new Stock().code(code).zhangTingCnt5(zhangTingCnt5Day).dieTingCnt5(dieTingCnt5Day));
//                }
                log.info("{} 5日涨停次数：{}，5日跌停次数{}", code, zhangTingCnt5Day, dieTingCnt5Day);
            }
            return stockList;
        } catch (Exception e) {
            log.error("选股网数据解析错误", e);
            throw new RuntimeException("选股网数据解析错误");
        }
    }
}
